package com.yu.util;


import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.yu.model.House;
import com.yu.model.Order;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;
import java.util.SortedMap;
import net.sf.json.JSONObject;

public class WeiXinUtil {
	
	public static String appid = "wx191fc28ce039710b";
	
	public static String appsecret = "4b87f32feac4006f396ec7ee2d7584e1";
	
    public static String URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;

    public static String url2 = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    public static  final String API_KEY = "gmWScaPGWmevgzTSvTx1naPoJx2Qc8Ls";
    
    
    
    public static void newOrderSms(String wxid,String order_detail){
    	JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        Map<String, Object> dataMap = new  HashMap<String, Object>();

        Map<String, String> first = new HashMap<String, String>();
        first.put("value","新订单提醒");
        first.put("color","#173177");
        dataMap.put("first", first);

        Map<String, String> keyword1 = new HashMap<String, String>();
        keyword1.put("value",DateUtil.wxDateTimeFormat.format(new Date()));
        keyword1.put("color","#173177");
        dataMap.put("keyword1", keyword1);

        Map<String, String> keyword2 = new HashMap<String, String>();
        keyword2.put("value","打扫服务");
        keyword2.put("color","#173177");
        dataMap.put("keyword2", keyword2);

        Map<String, String> keyword3 = new HashMap<String, String>();
        
        keyword3.put("value","已支付");
        keyword3.put("color","#173177");
        dataMap.put("keyword3", keyword3);
        Map<String, String> keyword4 = new HashMap<String, String>();
        
        keyword4.put("value","微信公众平台");
        keyword4.put("color","#173177");
        dataMap.put("keyword4", keyword4);
        
        Map<String, String> keyword5 = new HashMap<String, String>();
	    keyword5.put("value", order_detail);
        keyword5.put("color","#173177");
        dataMap.put("keyword5", keyword5);

        Map<String, String> remark = new HashMap<String, String>();
        remark.put("value","请及时处理,谢谢.");
        remark.put("color","#173177");
        dataMap.put("remark", remark);

        //orIpWxL2HUczxUUiCADz6KcdWMdU
        jsonMap.put("touser", wxid);
        jsonMap.put("template_id","wDLzIc_oDV9sSdLKvYfhlZJKfcNahXN1utJtaLKCwsc");
        jsonMap.put("url", "http://fangdong580.com/index/orderList");

        jsonMap.put("data",dataMap);

        JSONObject jsonData = JSONObject.fromObject(jsonMap);

        JSONObject jsonObject2 = CommonUtil.httpsRequest(url2+jsonObject.get("access_token"), "POST", jsonData.toString());
    	
    }
    
    public static void newHouseVerify(String wxid ,House house){
    	JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        Map<String, Object> dataMap = new  HashMap<String, Object>();

        Map<String, String> first = new HashMap<String, String>();
        first.put("value","您好,房源审核结果如下");
        first.put("color","#173177");
        dataMap.put("first", first);
//        Map<String, String> keyword1 = new HashMap<String, String>();
//        keyword1.put("value",DateUtil.wxDateTimeFormat.format(new Date()));
//        keyword1.put("color","#173177");
//        dataMap.put("keyword1", keyword1);

        Map<String, String> keyword2 = new HashMap<String, String>();
        keyword2.put("value","房源:"+house.getStr("name")+"信息,通过审核.");
        keyword2.put("color","#173177");
        dataMap.put("keyword2", keyword2);

        Map<String, String> remark = new HashMap<String, String>();
        remark.put("value","感谢您的使用.");
        remark.put("color","#173177");
        dataMap.put("remark", remark);

        //orIpWxL2HUczxUUiCADz6KcdWMdU
        jsonMap.put("touser", wxid);
        jsonMap.put("template_id","BQRoUPsDoxAN7LcFgdz4vHj53p9axYhAuaSRxgTTFZU");
        jsonMap.put("url", "http://fangdong580.com/index/house?id="+house.get("id"));

        jsonMap.put("data",dataMap);

        JSONObject jsonData = JSONObject.fromObject(jsonMap);

        JSONObject jsonObject2 = CommonUtil.httpsRequest(url2+jsonObject.get("access_token"), "POST", jsonData.toString());

    }
    
    // TODO 
    /*
    BQRoUPsDoxAN7LcFgdz4vHj53p9axYhAuaSRxgTTFZU
    开发者调用模版消息接口时需提供模版ID
    标题审核结果通知
    行业IT科技 - IT软件与服务
    详细内容
    {{first.DATA}}
    信息ID：{{keyword1.DATA}}
    详情：{{keyword2.DATA}}
    {{remark.DATA}}
    在发送时，需要将内容中的参数（{{.DATA}}内为参数）赋值替换为需要的信息
    内容示例
    您好，审核结果如下
    信息ID：30140603320008
    详情：备案内容通过审核
    感谢您的使用。
    */
    
    public static void moneyChangeNotice(String wxid ,BigDecimal changeMoney,BigDecimal balance){
    	JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        Map<String, Object> dataMap = new  HashMap<String, Object>();

        Map<String, String> first = new HashMap<String, String>();
        first.put("value","帐户资金变动提醒");
        first.put("color","#173177");
        dataMap.put("first", first);
//        Map<String, String> keyword1 = new HashMap<String, String>();
//        keyword1.put("value",DateUtil.wxDateTimeFormat.format(new Date()));
//        keyword1.put("color","#173177");
//        dataMap.put("keyword1", keyword1);

        Map<String, String> date = new HashMap<String, String>();
        date.put("value",DateUtil.wxDateTimeFormat.format(new Date()));
        date.put("color","#173177");
        dataMap.put("date", date);
        
        Map<String, String> adCharge = new HashMap<String, String>();
        adCharge.put("value","￥"+ changeMoney);
        adCharge.put("color","#173177");
        dataMap.put("adCharge", adCharge);

        Map<String, String> cashBalance = new HashMap<String, String>();
        cashBalance.put("value","￥"+ balance);
        cashBalance.put("color","#173177");
        dataMap.put("cashBalance", cashBalance);
        
        Map<String, String> remark = new HashMap<String, String>();
        remark.put("value","请点击查看");
        remark.put("color","#173177");
        dataMap.put("remark", remark);

        //orIpWxL2HUczxUUiCADz6KcdWMdU
        jsonMap.put("touser", wxid);
        jsonMap.put("template_id","i4igxSwf2IRVnKduvbQRFdCWwYGdLZH0yPJDboiCZzI");
        jsonMap.put("url", "http://fangdong580.com/index/main");

        jsonMap.put("data",dataMap);

        JSONObject jsonData = JSONObject.fromObject(jsonMap);

        JSONObject jsonObject2 = CommonUtil.httpsRequest(url2+jsonObject.get("access_token"), "POST", jsonData.toString());

    }
    /*
    i4igxSwf2IRVnKduvbQRFdCWwYGdLZH0yPJDboiCZzI
开发者调用模版消息接口时需提供模版ID
标题帐户资金变动提醒
行业IT科技 - IT软件与服务
详细内容
{{first.DATA}}

变动时间：{{date.DATA}}
变动金额：{{adCharge.DATA}}
{{type.DATA}}帐户余额：{{cashBalance.DATA}}
{{remark.DATA}}
在发送时，需要将内容中的参数（{{.DATA}}内为参数）赋值替换为需要的信息
内容示例
您好，您于2013/10/29  15:24 有一笔现金帐户充值到账：

变动时间：2013/11/26 14：00
变动金额：￥5618.63
现金帐户余额：￥8454.74
点击“查看详情“立即查阅您的帐户财务记录。
    
    
    
    
    模版IDdcveVmzDHnOIaRZD1Bni5vtPGUjdcdID74I5tbhXfJw
开发者调用模版消息接口时需提供模版ID
标题订单状态更新提醒
行业IT科技 - IT软件与服务
详细内容
{{first.DATA}}
更新时间：{{keyword1.DATA}}
订单类型：{{keyword2.DATA}}
订单状态：{{keyword3.DATA}}
订单来源：{{keyword4.DATA}}
订单详情：{{keyword5.DATA}}
{{remark.DATA}}
在发送时，需要将内容中的参数（{{.DATA}}内为参数）赋值替换为需要的信息
内容示例
订单状态更新提醒
更新时间：2014年11月5日 9点03分
订单类型：采购订单
订单状态：已审核通过
订单来源：上海客悦软件有限公司
订单详情：联想笔记本（型号）X1
订单已通过审核，如有疑问请致电。
    */
    
    public static void orderStatusUpdate(String wxid ,Object orderid,String statusName,String houseName){
    	JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        Map<String, Object> dataMap = new  HashMap<String, Object>();

        Map<String, String> first = new HashMap<String, String>();
        first.put("value","东家帮订单状态更新提醒");
        first.put("color","#173177");
        dataMap.put("first", first);
//        Map<String, String> keyword1 = new HashMap<String, String>();
//        keyword1.put("value",DateUtil.wxDateTimeFormat.format(new Date()));
//        keyword1.put("color","#173177");
//        dataMap.put("keyword1", keyword1);

        Map<String, String> keyword1 = new HashMap<String, String>();
        keyword1.put("value",DateUtil.wxDateTimeFormat.format(new Date()));
        keyword1.put("color","#173177");
        dataMap.put("keyword1", keyword1);
        
        Map<String, String> keyword2 = new HashMap<String, String>();
        keyword2.put("value","打扫服务");
        keyword2.put("color","#173177");
        dataMap.put("keyword2", keyword2);

        Map<String, String> keyword3 = new HashMap<String, String>();
        keyword3.put("value",statusName);
        keyword3.put("color","#173177");
        dataMap.put("keyword3", keyword3);
        
        Map<String, String> keyword4 = new HashMap<String, String>();
        keyword4.put("value","微信公众平台");
        keyword4.put("color","#173177");
        dataMap.put("keyword4", keyword4);
        
        Map<String, String> keyword5 = new HashMap<String, String>();
	    keyword5.put("value", houseName);
        keyword5.put("color","#173177");
        dataMap.put("keyword5", keyword5);
        
        Map<String, String> remark = new HashMap<String, String>();
        remark.put("value","请点击查看");
        remark.put("color","#173177");
        dataMap.put("remark", remark);

        //orIpWxL2HUczxUUiCADz6KcdWMdU
        jsonMap.put("touser", wxid);
        jsonMap.put("template_id","dcveVmzDHnOIaRZD1Bni5vtPGUjdcdID74I5tbhXfJw");
        jsonMap.put("url", "http://fangdong580.com/index/order_detail?id="+orderid);

        jsonMap.put("data",dataMap);

        JSONObject jsonData = JSONObject.fromObject(jsonMap);

        JSONObject jsonObject2 = CommonUtil.httpsRequest(url2+jsonObject.get("access_token"), "POST", jsonData.toString());

    }

    
    
    
    public static String createSign(String characterEncoding,SortedMap parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + API_KEY);
        String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }


    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };


    /**
     * @author 李欣桦
     * @date 2014-12-5下午2:32:05
     * @Description：将请求参数转换为xml格式的string
     * @param parameters  请求参数
     * @return
     */
    public static String getRequestXml(SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)) {
                sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
            }else {
                sb.append("<"+k+">"+v+"</"+k+">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }


    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader  bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            //log.error("连接超时：{}", ce);
        } catch (Exception e) {
            //log.error("https请求异常：{}", e);
        }
        return null;
    }

}
